﻿const express = require('express')
var router = express.Router()
const fs = require('pn/fs')
const multer = require('multer')
const path = require('path')
const jszip = require('jszip')
const { convert, convertFile } = require('convert-svg-to-png');
const svg2png = require('svg2png')

const { getSvgImage } = require('../utils.js')

const multipart = require('connect-multiparty');
var multipartMiddleware = multipart(); // 处理formdata表单数据中间件



var storage = multer.diskStorage({
	destination: './upload/',
	filename: function (req, file, cb) {
		//console.log(file)
		cb(null, file.originalname)
	},
})

// 定义上传的文件格式
var upload = multer({ 
	storage: storage
})

router.post('/svgtopng', async(req, res) => {
    let body = req.body;
    console.log(body)
    if (body.svg) {
      var reg = /(xlink:)?href=".*?"/ig
      body.svg = body.svg.replace(/\n/ig, ' ')
      var keyword = body.svg.match(reg)
      if (keyword && Array.isArray(keyword)) {
          keyword = Array.from(new Set(keyword))
          keyword.forEach(key => {
              var imgPath = key.replace(/(xlink:href=|")/ig, '')
              if ((imgPath.indexOf("img") !== -1) && (imgPath.indexOf("http") === -1)) {
                      var reg2 = new RegExp(imgPath, 'ig')
                      body.svg = body.svg.replace(reg2, 'http:' + imgPath)
              }
          })
      }

      const png = await convert(body.svg, {width: body.width});
      var delPath = path.resolve(`./public/thumb/${body.name}.png`)
      fs.writeFile(delPath, png)
    } else {
      body.svg = `<svg width="300" height="300" ></svg>`
      body.name = new Date().getTime()
      const png = await convert(body.svg);
      var delPath = path.resolve(`./public/thumb/${body.name}.png`)
      fs.writeFile(delPath, png)
    }
    
	let obj = { code: 1, path: `/thumb/${body.name}.png`}
    res.send(obj)
    
    setTimeout(() => {
        try {
            /**
             * @des 判断文件或文件夹是否存在
             */
            if (fs.existsSync(delPath)) {
                fs.unlinkSync(delPath);
            } else {
                console.log('inexistence path：', delPath);
            }
        } catch (error) {
            console.log('del error', error);
        }
    }, 60000)
})

router.post('/svgtopng/pro', async(req, res) => {
	let body = req.body;
    var result = await getSvgImage(body.svg)

    var imgPath = path.resolve(`./public/thumb/${result.name}.png`)

    fs.readFile(result.svg)
    .then(svg2png)
    .then(buffer => fs.writeFile(imgPath, buffer))
    .catch(e => console.error(e));
	let obj = { code: 1, path: `/thumb/${result.name}.png`}
    res.send(obj)
})


// 下载png
router.post('/downpng', async(req, res) => {
	let body = req.body,
		list = body.list,
		zip = new jszip(),
		width = Number(body.width), height = Number(body.height),
		ratio = height / width,
		max =3000;
		if (width > height) {
			if (width > max) {
				width =  max;
				height = width * ratio;
			}
		} else {
			if (height > max) {
				height = max;
				width = height / ratio;
			}
		}
	if (list.length > 1) {
		Promise.all(Array.from(list).map((item, i) => {
			return new Promise(async(resolve, reject)=> {
				let buff = await convert(item, {width, height});
				zip.file(body.name + i + '.png', buff)
				resolve(true)
			})
		})).then(files => {
			zip.generateAsync({
				// 压缩类型选择nodebuffer，在回调函数中会返回zip压缩包的Buffer的值，再利用fs保存至本地
				type: "nodebuffer",
				// 压缩算法
				compression: "DEFLATE",
				compressionOptions: {
					level: 9
				}
			}).then(function (content) {
				res.send(content)
			});
		})
	} else {
		let buff = await convert(list[0], {width, height})
		res.send(buff)
		
	}
})



module.exports = router;